import React from 'react';
import _ from 'lodash';
import classNames from 'classnames';
import { ISubmitEvent } from '../sys.dom';


interface IPaginationProps extends React.HTMLAttributes<HTMLUListElement> {
    /**
     * 总记录数，必须大于等于0。
     */
    count: number,
    /**
     * 当前页码，必须大于等于1。
     */
    current?: number,
    /**
     * 每页记录数，必须大于等于1。
     */
    pageSize: number,
    onPageSubmit?: (evt: ISubmitEvent<number>) => void;
}

const PAGINATION_VISIBLE_COUNT: number = 5;

const Pagination_ = (props: Readonly<IPaginationProps>): JSX.Element => {
    const { className, count, pageSize, current, ...restProps } = props;

    const formatPageIndex = (index: number): string => index.toString();

    const handleClick = (evt: React.MouseEvent<HTMLElement, MouseEvent>): void => {
        const index: number = parseInt(evt.currentTarget.getAttribute('data-index'), 10);
        props.onPageSubmit({ value: index });
    }

    if (count <= pageSize) {
        return null;
    } else {
        if (pageSize <= 0) {
            throw new Error('Illegal page size: ' + pageSize);
        }

        const pageCount = Math.floor((count - 1) / pageSize) + 1;

        if (current < 1 || current > pageCount) {
            throw new Error('Illegal current index: ' + current);
        }

        let pl: number;
        let ph: number;
        if (pageCount <= PAGINATION_VISIBLE_COUNT + 2) {
            // 全部显示
            pl = 2;
            ph = pageCount - 1;
        } else {
            const hp: number = Math.floor(PAGINATION_VISIBLE_COUNT / 2);
            pl = current - hp;
            ph = current + hp;
            if (pl <= 1) {
                pl = 2;
                ph = pl + PAGINATION_VISIBLE_COUNT - 1;
            } else if (ph >= pageCount) {
                ph = pageCount - 1;
                pl = ph - PAGINATION_VISIBLE_COUNT + 1;
            }
        }

        const indexes = _.range(pl, ph + 1);

        return <ul className={classNames('ui pagination menu', className)} {...restProps}>
            {
                current === 1 ?
                    <>
                        <li className="icon item disabled"><i className="left chevron icon" /></li>
                        <li className="item active">
                            {formatPageIndex(1)}
                        </li>
                    </>
                    :
                    <>
                        <li className="icon item" style={{ cursor: 'pointer' }} data-index={current - 1} onClick={handleClick}><i className="left chevron icon" /></li>
                        <li className="item" style={{ cursor: 'pointer' }} data-index={1} onClick={handleClick}>{formatPageIndex(1)}</li>
                    </>
            }
            {pl > 2 && <li className="item disabled">&nbsp;...&nbsp;</li>}
            {
                indexes.map(index =>
                    index === current ?
                        <li key={index} className="item active">
                            {index}
                        </li>
                        :
                        <li key={index} className="item" style={{ cursor: 'pointer' }} data-index={index} onClick={handleClick}>{formatPageIndex(index)}</li>
                )
            }
            {ph < pageCount - 1 && <li className="item disabled"><span className="page-link">&nbsp;...&nbsp;</span></li>}
            {
                current === pageCount ?
                    <>
                        <li className="item active">
                            {formatPageIndex(pageCount)}
                        </li>
                        <li className="item disabled"><i className="right chevron icon" /></li>
                    </>
                    :
                    <>
                        <li className="item" style={{ cursor: 'pointer' }} data-index={pageCount} onClick={handleClick}>{formatPageIndex(pageCount)}</li>
                        <li className="item" style={{ cursor: 'pointer' }} data-index={current + 1} onClick={handleClick}><i className="right chevron icon" /></li>
                    </>
            }
        </ul>;
    }
};

Pagination_.defaultProps = {
    current: 1,
    onPageSubmit: (evt: ISubmitEvent<number>): void => console.warn('Pagination changed but unhandled'),
};

const Pagination = React.memo(Pagination_);

export { Pagination };